package com.zluyuer.ermu;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.net.Socket;

import com.zluyuer.ermu.msg.Message;
import com.zluyuer.ermu.msg.MessageExecutor;
import com.zluyuer.ermu.msg.MessageHandler;
import com.zluyuer.ermu.msg.MessageParser;

public class ErmuUtil {
    
    public static void register(Class<? extends Message> clazz, MessageHandler handler) {
        Method method = null;
        try {
            method = clazz.getMethod("getMsgCode");
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("Message doesn't have \"getMsgCode\" method");
        }
        
        String msgCode = "";
        try {
            Message msg = clazz.newInstance();
            msgCode = (String)method.invoke(msg);
        } catch (Exception e) {
            throw new IllegalArgumentException("Error execute getMsgCode");
        }
        
        MessageParser.register(msgCode, clazz);
        MessageExecutor.register(msgCode, handler);
    }

    public static PrintWriter getSocketPrintWriter(Socket socket) 
        throws IOException {
        
        OutputStream socketOut = socket.getOutputStream();
        return new PrintWriter(new OutputStreamWriter(socketOut, "UTF-8"), true);
    }
    
    public static InputStreamReader getSocketReader(Socket socket) 
        throws IOException {
        
        InputStream socketIn = socket.getInputStream();
        return new InputStreamReader(socketIn, "UTF-8");
    }
}
